﻿using System;
using System.Linq;
using System.Collections.Generic;
using Castle.Core.Interceptor;
using Castle.DynamicProxy;
using Microsoft.SharePoint.Administration;
using Trentacular.SharePoint.Deployment.Collections;
using Trentacular.SharePoint.Deployment.Data.Proxy;
using Trentacular.SharePoint.Deployment.Model;
using Microsoft.SharePoint;

namespace Trentacular.SharePoint.Deployment.Data
{
    public class AppData
    {
        #region Proxy Helpers

        private ProxyGenerator _proxyGenerator;
        protected ProxyGenerator ProxyGenerator
        {
            get
            {
                if (_proxyGenerator == null)
                    _proxyGenerator = new ProxyGenerator();
                return _proxyGenerator;
            }
        }

        public IList<T> CreateProxiedList<T>(IInterceptor initializer)
        {
            return (IList<T>)ProxyGenerator.CreateClassProxy(
                typeof(VirtualList<T>),
                new Type[] { typeof(ILazyInitializingListProxy) },
                initializer
                );
        }

        #endregion

        public Farm Farm { get; private set; }

        public AppData()
        {
            var spFarm = SPFarm.Local;

            Farm = new Farm
                {
                    Id = spFarm.Id,
                    Name = spFarm.Name,
                    DisplayName = spFarm.DisplayName
                };

            Farm.WebApplications = CreateProxiedList<WebApplication>(
                new FarmWebApplicationsLazyInitializer { Owner = Farm }
                );

            Farm.Solutions = CreateProxiedList<Solution>(
                new FarmSolutionsLazyInitializer { Owner = Farm }
                );

            //Farm.AllFeatureDefinitions = CreateProxiedList<FeatureDefinition>(
            //    new FarmFeatureDefinitionsLazyInitializer { Owner = Farm }
            //    );

            Farm.Features = CreateProxiedList<FarmFeature>(
                new FarmFeaturesLazyInitializer { Owner = Farm }
                );
        }
    }
}
